<template>
  <div>
    <!-- 模块选择 -->
    <div class="module-selector">
      <el-radio-group v-model="activeModule" @change="handleModuleChange">
        <el-radio-button label="attendance">学生考勤</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="query">
        <el-form-item label="姓名">
          <el-input v-model="query.realName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="query.grade" placeholder="请选择年级" clearable style="width: 150px">
            <el-option label="一年级" :value="1" />
            <el-option label="二年级" :value="2" />
            <el-option label="三年级" :value="3" />
            <el-option label="四年级" :value="4" />
            <el-option label="五年级" :value="5" />
            <el-option label="六年级" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="query.classNum" placeholder="请选择班级" clearable style="width: 150px">
            <el-option label="1班" :value="1" />
            <el-option label="2班" :value="2" />
            <el-option label="3班" :value="3" />
            <el-option label="4班" :value="4" />
            <el-option label="5班" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="query.checkType" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="出校" value="出校" />
            <el-option label="进校" value="进校" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="exportToExcel">导出Excel</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="container">
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="realName" label="姓名"  align="center" />
        <el-table-column prop="grade" label="年级" align="center" />
        <el-table-column prop="classNum" label="班级"  align="center" />
        <el-table-column prop="checkType" label="类型"  align="center" />
        <el-table-column prop="checkTime" label="时间"  align="center" />
        <el-table-column label="操作"  align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="page.index"
          v-model:page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="changePage"
          @size-change="handleSizeChange"
      />

      <div class="toolbar-container">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAttendanceRecords, deleteAttendanceRecord, recordAttendance,batchDeleteAttendance } from '@/api/attendance';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const moduleNames = {
  attendance: '学生考勤'
};

const activeModule = ref<'attendance'>('attendance');

const query = reactive({
  realName: '',
  grade: null,
  classNum: null,
  checkType: ''
});

const tableData = ref([]);
const selectedIds = ref([]);

const page = reactive({
  index: 1,
  size: 10,
  total: 0
});

// 获取数据
const getData = async () => {
  try {
    const { data } = await getAttendanceRecords({
      ...query,
      page: page.index,
      pageSize: page.size
    });
    tableData.value = data.list;
    page.total = data.total;
  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};

// 搜索
const handleSearch = () => {
  getData();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(query).forEach(key => query[key] = '');
  getData()
};

// 删除单条记录
const handleDelete = async (row: any) => {
  try {
    const confirm = await ElMessageBox.confirm('确定删除该考勤记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if (confirm) {
      await deleteAttendanceRecord(row.id);
      ElMessage.success('删除成功');
      getData();
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  const confirm = await ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  if (confirm) {
    await batchDeleteAttendance(selectedIds.value);
    ElMessage.success('删除成功');
    getData();
  }
};

// 进校打卡
const checkIn = () => {
  const data = {
    studentId: 1,
    checkType: '进校',  // 传递一个对象，其中包含 checkType 字段
    realName: "张三",
    grade: 1,
    classNum: 4
  };
  recordAttendance(data)
};

// 出校打卡
const checkOut = () => {
  const data = {
    studentId: 1,
    checkType: '出校',  // 传递一个对象，其中包含 checkType 字段
    realName: "张三",
    grade: 1,
    classNum: 4
  };
  recordAttendance(data)
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 分页控制
const changePage = (val: number) => {
  page.index = val;
  getData();
};

const handleSizeChange = (val: number) => {
  page.size = val;
  getData();
};

//导出方法
const exportToExcel = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('暂无数据可导出');
    return;
  }

  // 1. 构造导出的 JSON 数据
  const exportData = tableData.value.map(item => ({
    姓名: item.realName,
    年级: item.grade,
    班级: item.classNum,
    类型: item.checkType,
    时间: item.checkTime
  }));

  // 2. 转为工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData);

  // 3. 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '考勤记录');

  // 4. 导出文件
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
  saveAs(blob, `考勤记录_${new Date().toLocaleDateString()}.xlsx`);
};


onMounted(()=>{
  const socket = new WebSocket('ws://localhost:8081/attendance/socket');

  socket.onmessage = function (event){
    const newAttendance = JSON.parse(event.data);
    console.log('接收到打卡更新消息：',newAttendance);
    // tableData.value.unshift(newAttendance);
    getData();
    ElMessage.success(`${newAttendance.checkTime} ${newAttendance.grade}年级${newAttendance.classNum}班学生
    ${newAttendance.realName}打卡成功，类型：${newAttendance.checkType}`)
  };

  socket.onclose=()=>{
    console.log('webSocket 连接已关闭');
  }

  socket.onerror=(error)=>{
    console.error('webSocket 错误',error);
  }

})

getData();
</script>

<style scoped>
.module-selector {
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 15px;
  background: #fff;
  margin-bottom: 15px;
  border-radius: 4px;
}

.container {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  position: relative;
}

.toolbar-container {
  margin: 20px 0;
  text-align: right;
}

.el-table {
  margin-bottom: 15px;
  width: 100%;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 15px;
}

.attendance-buttons {
  position: fixed;
  bottom: 20px;
  left: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attendance-btn {
  width: 100px;
}
</style>
